//
//  HttpTool.m
//  Project
//
//  Created by  CarlsonLee on 2018/12/11.
//  Copyright © 2018年 YANJING. All rights reserved.
//

#import "HttpTool.h"

@implementation HttpTool

+ (void)prepareManager:(AFURLSessionManager *)manager
{
    // 1.初始化单例类
    // 2.设置证书模式
    NSString * cerPath = [[NSBundle mainBundle] pathForResource:@"server" ofType:@"cer"];
    NSData * cerData = [NSData dataWithContentsOfFile:cerPath];
    AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:[[NSSet alloc] initWithObjects:cerData, nil]];;
    // 客户端是否信任非法证书
    policy.allowInvalidCertificates = YES;
    // 是否在证书域字段中验证域名
    [policy setValidatesDomainName:NO];
    manager.securityPolicy = policy;
}

+ (NSURLSessionDataTask *)myOriRequestWithBaseUrl:(NSString *)baseUrl urlStr:(NSString *)urlStr method:(NSString *)methodStr parameters:(NSDictionary *)parameters completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
    if (parameters) {
        [tempDic setValuesForKeysWithDictionary:parameters];
    }
    NSMutableURLRequest * request = [[AFJSONRequestSerializer serializer] requestWithMethod:methodStr URLString:[NSString stringWithFormat:@"%@%@",baseUrl,urlStr] parameters:tempDic error:nil];
    request.timeoutInterval = 15;
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:completionHandler];
    [dataTask resume];
    return dataTask;
}

+ (NSURLSessionDataTask *)myRequestWithBaseUrl:(NSString *)baseUrl urlStr:(NSString *)urlStr method:(NSString *)methodStr parameters:(NSDictionary *)parameters success:(void (^)(NSObject *resultObj))success fail:(void (^)(NSString *errorStr))fail
{
    return [HttpTool myOriRequestWithBaseUrl:baseUrl urlStr:urlStr method:methodStr parameters:parameters completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if(error){
            if (error.code==-1001) {
                if(fail)fail(@"请求超时");
                return;
            }
            if(fail)fail(@"网络异常");
        }else{
            NSDictionary *dic = responseObject;
            if (dic&&[dic isKindOfClass:[NSDictionary class]]) {
                NSObject *codeStr = dic[@"returnCode"];
                if ([codeStr isKindOfClass:[NSNull class]]) {
                    if(fail)fail(@"请求失败");
                    return;
                }
                id dataStr = dic[@"data"];
                if([dic[@"returnCode"] intValue]==200){
                    id dataStr = dic[@"data"];
                    if([dataStr isKindOfClass:[NSString class]]){
                        id resultData = [self handleDataStr:dataStr];
                        if(success)success(resultData);
                        return;
                    }else{
                        if(success)success(dataStr);
                        return;
                    }
                }else{
                    if(fail)fail(dic[@"errorMsg"]);
                }
            }else{
                if(fail)fail(@"请求失败");
            }
        }
    }];
}



+ (NSURLSessionUploadTask *)myRequestMultiUploadWithBaseUrl:(NSString *)baseUrl urlStr:(NSString *)urlStr parameters:(NSDictionary *)paramaters project:(NSDictionary *)projects success:(void (^)(NSObject *resultObj))success fail:(void (^)(NSString *errorStr))fail
{
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@%@", baseUrl, urlStr] parameters:paramaters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (id key in [projects allKeys]) {
            //代表的文件对应的参数
            NSString *name = key;
            //文件的名字
            NSString *fileName = [NSString stringWithFormat:@"%@.jpg", name];
            NSData *data;
            id proData = [projects objectForKey:key];
            if ([proData isKindOfClass:[NSString class]]) {
                NSURL *fileUrl = [NSURL fileURLWithPath:proData];
                NSString *extension = fileUrl.pathExtension;
                NSString* mineType = @"";
                fileName = [fileUrl lastPathComponent];
                if([extension isEqualToString:@"jpg"] || [extension isEqualToString:@"jpeg"] || [extension isEqualToString:@"png"]){
                    mineType = [NSString stringWithFormat:@"image/%@", extension];
                }else if ([extension isEqualToString:@"mp4"]){
                    mineType = [NSString stringWithFormat:@"video/%@", extension];
                }else{
                    
                }
                [formData appendPartWithFileURL:fileUrl name:name fileName:fileName mimeType:mineType error:nil];
            } else if ([proData isKindOfClass:[UIImage class]]) {
                data = UIImageJPEGRepresentation(proData, 1.0);
                [formData appendPartWithFileData:data name:name fileName:fileName mimeType:@"image/jpeg"];
            }else if ([proData isKindOfClass:[NSData class]]){
                
                data = proData;
                [formData appendPartWithFileData:data name:name fileName:fileName mimeType:@"image/jpeg"];
            } else{
                data = [NSData dataWithContentsOfURL:proData];
                while (data == nil) {
                    data = [NSData dataWithContentsOfURL:proData];
                }
                [formData appendPartWithFileData:data name:name fileName:fileName mimeType:@"image/jpeg"];
            }
            
        }
        
    } error:nil];
    request.timeoutInterval = 60;
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSURLSessionUploadTask *uploadTask;
    uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            if (error.code==-1001) {
                fail(@"请求超时");
                return;
            }
            fail(@"网络异常");//网络链接问题或者请求地址有误
        } else {
            NSDictionary *dic = responseObject;
            if (dic&&[dic isKindOfClass:[NSDictionary class]]) {
                NSObject *codeStr = dic[@"returnCode"];
                if ([codeStr isKindOfClass:[NSNull class]]) {
                    fail(@"请求失败");
                    return;
                }
                id resultData = dic[@"data"];
                if ([dic[@"returnCode"] intValue]==200) {
                    success(resultData);
                    return;
                }else{
                    NSString *msg = dic[@"errorMsg"];
                    if (msg&&[msg isKindOfClass:[NSString class]]) {
                        fail(msg);
                    }else{
                        fail(@"请求失败");//未返回错误信息
                    }
                }
            }else{
                fail(@"请求失败");//返回数据格式错误
            }
        }
        
    }];
    
    [uploadTask resume];
    
    return uploadTask;
}

+ (id)handleDataStr:(id)responseObject
{
    if(!NSStringIsEmpty(responseObject)){
        if([responseObject rangeOfString:@"{"].location != NSNotFound){
            responseObject = [responseObject gel_jsonValueDecoded];
        }
    }
    return responseObject;
}

@end
